package mobi.smarthosts;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class HttpHelper {

    public static final String CONTENT_TYPE_JSON = "application/json";
    public static final String CONTENT_TYPE_XML = "text/xml";
    public static final String CONTENT_TYPE_JPEG = "image/jpeg";
    public static final String CONTENT_TYPE_PNG = "image/png";
    public static final String CONTENT_TYPE_GZIP = "application/x-gzip-compressed";
    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private static final int IO_BUFFER_SIZE = 4 * 1024;

    public static String simpleHttpRequestString(String urlString) {
        try {
            return new String(simpleHttpRequest(urlString), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new SmartHostsException(e);
        }
    }

    public static Bitmap simpleHttpRequestBitmap(String urlString) {
        byte[] data = simpleHttpRequest(urlString);
        return BitmapFactory.decodeByteArray(data, 0, data.length);
    }

    public static byte[] simpleHttpRequest(String urlString) {
        if (Utils.isEmptyString(urlString)) return null;

        InputStream httpStream = null;
        InputStream in = null;
        OutputStream out = null;

        try {
            URL url = new URL(urlString);
            if (url.getProtocol().equals("https"))
                url = new URL(urlString.replaceAll("https://", "http://"));

            httpStream = url.openStream();
            in = new BufferedInputStream(httpStream, IO_BUFFER_SIZE);

            ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
            copy(in, out);
            out.flush();

            return dataStream.toByteArray();
        } catch (MalformedURLException e) {
            throw new SmartHostsException(e);
        } catch (IOException e) {
            throw new SmartHostsException(e.getMessage(), e);
        } finally {
            Utils.closeStream(httpStream);
            Utils.closeStream(in);
            Utils.closeStream(out);
        }
    }

    private static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] b = new byte[IO_BUFFER_SIZE];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }

}
